package main

import (
	"encoding/json"
	"net/http"

	"github.com/gorilla/mux"
	"github.com/gorilla/schema"
)

var decoder = schema.NewDecoder()

type Ret struct {
	RetCode int         `json:"ret"`
	Message string      `json:"msg"`
	Data    interface{} `json:"data"`
}

func Handle(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	method, ok := vars["method"]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	server, ok := registerServer[method]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	var err error
	err = r.ParseForm()
	if err != nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	req := server.MakeRequest()
	err = decoder.Decode(req, r.PostForm)
	if err != nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	rsp := server.Handle(req)
	ret := &Ret{
		RetCode: 0,
		Message: "ok",
		Data:    rsp,
	}
	b, err := json.Marshal(ret)
	if err != nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	w.Write(b)
}
